//
//  SAPayDocumentsVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/8/27.
//

#import "SAPayDocumentsVC.h"
#import "SASaleDocumentsCell.h"
#import "HDDatePickerView.h"
#import "SAPayDocumentsModel.h"
#import "SAProductVipScreeningView.h"
#import "SAInvoiceGetConditionAPI.h"
#import "SAPayDocumentsDetailVC.h"
#import "SAReceiveListAPI.h"

@interface SAPayDocumentsVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) UIView *topContentView;
@property (nonatomic, strong) UILabel *startLab;
@property (nonatomic, strong) UILabel *startDateLab;
@property (nonatomic, strong) UILabel *endLab;
@property (nonatomic, strong) UILabel *endDateLab;
@property (nonatomic, strong) UIImageView *iconImageV;
@property (nonatomic, strong) UIButton *startDateBtn;
@property (nonatomic, strong) UIButton *endDateBtn;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) SAReceiveListAPI *receiveListAPI;
@property (nonatomic, strong) NSMutableArray<SAPayDocumentsModel *> *dataMarr;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) UILabel *saleNumLab;
@property (nonatomic, assign) UILabel *saleCountLab;
@property (nonatomic, strong) NSMutableArray<SAProductHomeScreeningModel *> *screenArray;
@property (nonatomic, strong) SAInvoiceGetConditionAPI *invoiceGetConditionAPI;

@property (nonatomic, strong) NSString *memberName;
@property (nonatomic, strong) NSString *memberId;
@property (nonatomic, strong) UIView *tipView;

@end

@implementation SAPayDocumentsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (self.receiveListAPI == api) {
        if (self.currentPage == 1) {
            NSString *totalCount = data[@"data"][@"obj"][@"totalCount"];
            NSString *actualPrice = data[@"data"][@"obj"][@"totalPrice"];
            self.saleNumLab.text = [NSString stringWithFormat:@"%0.lf",[totalCount doubleValue]];
            self.saleCountLab.text = [NSString stringWithFormat:@"%0.2lf",[actualPrice doubleValue]/100.f];
            [self.dataMarr removeAllObjects];
        }
        NSMutableArray<SAInvoiceListModel *> *marr = [SAPayDocumentsModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
        for (SAPayDocumentsModel *model in marr) {
            [self.dataMarr addObject:model];
        }
        self.tipView.hidden = self.dataMarr.count > 0;
        [self.tableView reloadData];
    }else if (self.invoiceGetConditionAPI == api) {
        NSMutableArray<SAProductHomeScreeningModel *> *marr = [SAProductHomeScreeningModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        for (SAProductHomeScreeningModel *model in marr) {
            if ([model.name isEqualToString:@"店员"]) {
                if (model.voList.count > 0) {
                    model.voList[0].check = YES;
                }
                [self.screenArray addObject:model];
            }
            if ([model.name isEqualToString:@"支付方式"]) {
                if (model.voList.count > 0) {
                    model.voList[0].check = YES;
                }
                [self.screenArray addObject:model];
            }
            if ([model.name isEqualToString:@"订单状态"]) {
                NSMutableArray <SAProductHomeScreeningList *>*voList = [NSMutableArray array];
                for (SAProductHomeScreeningList *list in model.voList) {
                    if (![list.attrName isEqualToString:@"已退款"] && ![list.attrName isEqualToString:@"部分退"]) {
                        [voList addObject:list];
                    }
                }
                model.voList = voList;
                if (model.voList.count > 2) {
                    model.voList[2].check = YES;
                }
                [self.screenArray addObject:model];
            }
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}


#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SASaleDocumentsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SASaleDocumentsCell" forIndexPath:indexPath];
    cell.payModel = self.dataMarr[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SAPayDocumentsModel *model = self.dataMarr[indexPath.row];
    SAPayDocumentsDetailVC *pushVC = [[SAPayDocumentsDetailVC alloc] initWithOrderId:model.receiveOrderId];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(71);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"收款单据"];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    self.currentPage = 1;
    self.memberName = @"";
    self.memberId = @"";
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [searchBtn setImage:[UIImage imageNamed:@"Sale_screen"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(clickedSearchBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addRightViews:@[searchBtn]];
    
    [self.view addSubview:self.topContentView];
    [self.topContentView addSubview:self.startLab];
    [self.topContentView addSubview:self.startDateLab];
    [self.topContentView addSubview:self.endLab];
    [self.topContentView addSubview:self.endDateLab];
    [self.topContentView addSubview:self.iconImageV];
    [self.topContentView addSubview:self.startDateBtn];
    [self.topContentView addSubview:self.endDateBtn];
    
    [self.topContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kScaleNum(StatusHeight));
        make.height.mas_equalTo(kScaleNum(44));
        make.right.mas_equalTo(0);
        make.left.mas_equalTo(kScaleNum(0));
    }];
    
    [self.iconImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(29, 29));
    }];
    
    [self.startLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.startDateLab);
        make.top.mas_equalTo(kScaleNum(2));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.startDateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.iconImageV.mas_left).offset(kScaleNum(-68));
        make.top.mas_equalTo(kScaleNum(22));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.endLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.endDateLab);
        make.top.mas_equalTo(kScaleNum(2));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.endDateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.iconImageV.mas_right).offset(kScaleNum(68));
        make.top.mas_equalTo(kScaleNum(22));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.startDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.startDateLab);
        make.top.bottom.mas_equalTo(0);
    }];
    
    [self.endDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.endDateLab);
        make.top.bottom.mas_equalTo(0);
    }];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    _startDateLab.text = timeFormatStr;
    _endDateLab.text = timeFormatStr;
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 49), kScreenWidth, kScaleNum(48))];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    UILabel *saleNumLab = [[UILabel alloc] initWithFrame:CGRectMake(kScaleNum(50), kScaleNum(7), kScaleNum(120), kScaleNum(15))];
    saleNumLab.text = @"0";
    saleNumLab.textColor = kPinkColor;
    saleNumLab.font = kFont(15);
    saleNumLab.textAlignment = NSTextAlignmentCenter;
    [whiteView addSubview:saleNumLab];
    self.saleNumLab = saleNumLab;
    
    UILabel *saleNumTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(kScaleNum(50), kScaleNum(26), kScaleNum(120), kScaleNum(15))];
    saleNumTitleLab.text = @"收款数";
    saleNumTitleLab.textColor = kBlackColor;
    saleNumTitleLab.font = kFont(15);
    saleNumTitleLab.textAlignment = NSTextAlignmentCenter;
    [whiteView addSubview:saleNumTitleLab];
    
    UILabel *saleCountLab = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(170), kScaleNum(7), kScaleNum(120), kScaleNum(15))];
    saleCountLab.text = @"0";
    saleCountLab.textColor = kPinkColor;
    saleCountLab.font = kFont(15);
    saleCountLab.textAlignment = NSTextAlignmentCenter;
    [whiteView addSubview:saleCountLab];
    self.saleCountLab = saleCountLab;
    
    UILabel *saleCountTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(170), kScaleNum(26), kScaleNum(120), kScaleNum(15))];
    saleCountTitleLab.text = @"收款额";
    saleCountTitleLab.textColor = kBlackColor;
    saleCountTitleLab.font = kFont(15);
    saleCountTitleLab.textAlignment = NSTextAlignmentCenter;
    [whiteView addSubview:saleCountTitleLab];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.tipView];
    
    self.receiveListAPI.currentPage = 1;
    self.receiveListAPI.pageSize = 20;
    self.receiveListAPI.startTime = timeFormatStr;
    self.receiveListAPI.endTime = timeFormatStr;
    [self.receiveListAPI sendRequestToServerWithActivityViewAndMask:GET];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    }];
    MJRefreshAutoStateFooter *mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage ++;
        [weakSelf loadData];
    }];
    [mj_footer setTitle:@"已经到底啦~" forState:MJRefreshStateIdle];//设置闲置状态下不显示“点击或上拉加载更多”
    self.tableView.mj_footer = mj_footer;
    
    [self.invoiceGetConditionAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(void)loadData {
    if (self.memberName.length > 0) {
        self.receiveListAPI.memberId = self.memberId;
    }else {
        self.receiveListAPI.memberId = @"";
    }
    self.receiveListAPI.empId = @"";
    self.receiveListAPI.payType = @"";
    self.receiveListAPI.status = @"";
    for (SAProductHomeScreeningModel *model in self.screenArray) {
        if ([model.name isEqualToString:@"店员"]) {
            for (SAProductHomeScreeningList *list in model.voList) {
                if (list.check == YES && ![list.attrName isEqualToString:@"全部"]) {
                    self.receiveListAPI.empId = [NSString stringWithFormat:@"%zd",list.attrId];
                }
            }
        }
        if ([model.name isEqualToString:@"支付方式"]) {
            for (SAProductHomeScreeningList *list in model.voList) {
                if (list.check == YES && ![list.attrName isEqualToString:@"全部"]) {
                    self.receiveListAPI.payType = [NSString stringWithFormat:@"%zd",list.attrId];
                }
            }
        }
        if ([model.name isEqualToString:@"订单状态"]) {
            for (SAProductHomeScreeningList *list in model.voList) {
                if (list.check == YES) {
                    if ([list.attrName isEqualToString:@"全部"]) {
                        self.receiveListAPI.status = @"";
                    }else {
                        self.receiveListAPI.status = [NSString stringWithFormat:@"%zd",list.attrId];
                    }
                }
            }
        }
    }
    self.receiveListAPI.currentPage = self.currentPage;
    [self.receiveListAPI sendRequestToServerWithActivityViewAndMask:GET];
}

#pragma mark - initUI
-(void)clickedSearchBtn {
    __weak typeof(self) weakSelf = self;
    SAProductVipScreeningView *screenView = [SAProductVipScreeningView shareCornView];
    screenView.delegate = self;
    [screenView loadData:self.screenArray MemberName:self.memberName MemberId:self.memberId];
    screenView.screeningBlock = ^(NSMutableArray *selectedArray, NSString *memberName, NSString *memberId) {
        if (memberName.length > 0) {
            weakSelf.memberName = memberName;
            weakSelf.memberId = memberId;
        }else {
            weakSelf.memberName = @"";
            weakSelf.memberId = @"";
        }
        weakSelf.currentPage = 1;
        weakSelf.screenArray = selectedArray;
        [weakSelf loadData];
    };
    [screenView showView:self];
}

- (void)clickStartDateBtn:(UIButton *)btn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.startDateLab.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        NSDate *date1 = [self.dateFormatter dateFromString:selectedDate];
        NSDate *date2 = [self.dateFormatter dateFromString:weakSelf.endDateLab.text];
        if ([date1 compare:date2] == NSOrderedDescending) {
            [Prompt popPromptViewWithMsg:@"开始日期不能大于截止日期" duration:2];
        }else {
            weakSelf.startDateLab.text = selectedDate;
            weakSelf.currentPage = 1;
            weakSelf.receiveListAPI.startTime = selectedDate;
            [weakSelf loadData];
        }
    };
}

- (void)clickEndDateBtn:(UIButton *)btn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.endDateLab.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        NSDate *date1 = [self.dateFormatter dateFromString:selectedDate];
        NSDate *date2 = [self.dateFormatter dateFromString:weakSelf.startDateLab.text];
        if ([date1 compare:date2] == NSOrderedAscending) {
            [Prompt popPromptViewWithMsg:@"截止日期不能小于开始日期" duration:2];
        }else {
            weakSelf.endDateLab.text = selectedDate;
            weakSelf.currentPage = 1;
            weakSelf.receiveListAPI.endTime = selectedDate;
            [weakSelf loadData];
        }
    };
}

#pragma mark - lazy
- (UIView *)topContentView {
    if (!_topContentView) {
        _topContentView = [[UIView alloc] init];
        _topContentView.backgroundColor = [UIColor whiteColor];
    }
    return _topContentView;
}

- (UILabel *)startLab {
    if (!_startLab) {
        _startLab = [[UILabel alloc] init];
        _startLab.textColor = kBlackColor;
        _startLab.font = kFont(15);
        _startLab.text = @"开始";
    }
    return _startLab;
}

- (UILabel *)startDateLab {
    if (!_startDateLab) {
        _startDateLab = [[UILabel alloc] init];
        _startDateLab.textColor = kBlackColor;
        _startDateLab.font = kFont(15);
    }
    return _startDateLab;
}

- (UILabel *)endLab {
    if (!_endLab) {
        _endLab = [[UILabel alloc] init];
        _endLab.textColor = kBlackColor;
        _endLab.font = kFont(15);
        _endLab.text = @"截止";
    }
    return _endLab;
}

- (UILabel *)endDateLab {
    if (!_endDateLab) {
        _endDateLab = [[UILabel alloc] init];
        _endDateLab.textColor = kBlackColor;
        _endDateLab.font = kFont(15);
    }
    return _endDateLab;
}

- (UIImageView *)iconImageV {
    if (!_iconImageV) {
        _iconImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SA_to"]];
    }
    return _iconImageV;
}

- (UIButton *)startDateBtn {
    if (!_startDateBtn) {
        _startDateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_startDateBtn addTarget:self action:@selector(clickStartDateBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _startDateBtn;
}

- (UIButton *)endDateBtn {
    if (!_endDateBtn) {
        _endDateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_endDateBtn addTarget:self action:@selector(clickEndDateBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endDateBtn;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 98), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 98)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SASaleDocumentsCell class] forCellReuseIdentifier:@"SASaleDocumentsCell"];
    }
    return _tableView;
}

-(UIView *)tipView {
    if (!_tipView) {
        _tipView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 44), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 44))];
        _tipView.backgroundColor = [UIColor whiteColor];
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Shop_search2"]];
        icon.frame = SARectMake(124, 106, 138, 83);
        [_tipView addSubview:icon];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + kScaleNum(20), _tipView.width, kScaleNum(20))];
        titleLab.text = @"暂无相关信息";
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = kGrayColor;
        [_tipView addSubview:titleLab];
    }
    return _tipView;
}

-(NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [NSDateFormatter new];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

-(SAReceiveListAPI *)receiveListAPI {
    if (!_receiveListAPI) {
        _receiveListAPI = [SAReceiveListAPI apiWithDelegate:self];
    }
    return _receiveListAPI;
}

-(NSMutableArray<SAPayDocumentsModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SAInvoiceGetConditionAPI *)invoiceGetConditionAPI {
    if (!_invoiceGetConditionAPI) {
        _invoiceGetConditionAPI = [SAInvoiceGetConditionAPI apiWithDelegate:self];
    }
    return _invoiceGetConditionAPI;
}

-(NSMutableArray<SAProductHomeScreeningModel *> *)screenArray {
    if (!_screenArray) {
        _screenArray = [NSMutableArray array];
    }
    return _screenArray;
}

@end
